package cn.gpnusz.oliverwiki.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author h0ss
 * @description
 * @date 2021/10/12 21:45
 */
@Component
public class RedisUtil {

    private static final Logger LOG = LoggerFactory.getLogger(RedisUtil.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     *
     * @param key : IP+文章的组合
     * @param second : redis过期时间
     * @return : true表示key不存在，false表示key存在
     * @author h0ss
     */
    public boolean validateRepeat(String key, long second) {
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            LOG.info("key已存在：{}", key);
            return false;
        } else {
            LOG.info("key不存在，放入：{}，过期 {} 秒", key, second);
            stringRedisTemplate.opsForValue().set(key, key, second, TimeUnit.SECONDS);
            return true;
        }
    }
}
